#!/usr/bin/env python
# -*- coding: utf-8 -*-

import datetime
import json
from cache.topic_gallery_cache import get_topic_gallery_cache

import tornado
import tornado.web
from utils import file_util
from utils import log
from config import etc
from controls import mongo
from controls import data_topic_title_mysql
from controls import data_topic_like_mysql
from controls import data_prov_base_mysql
from controls import data_img_base_mysql
from controls import data_topic_note_mysql
from utils.session_base import ApiGuest, ApiHost
from utils.session_mc import BaseHandler
from controls import data_user_feed_mysql


class ListHandler(BaseHandler):
    @ApiGuest
    def post(self):
        if self.current_user:
            userid = self.current_user['userid']
        else:
            userid = None
        provid = self.ss_params['provid']

        begin = self.ss_params['begin']
        limit = self.ss_params['limit']

        log.i("[provid: %d]" % provid)
        log.i("[begin: %d]" % begin)
        log.i("[limit: %d]" % limit)

        if begin and limit is None:
            log.e('params fetching error')
            res = {'idx': self.ss_idx, 'ret': 1, 'msg': etc.err_500, 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return

        if type(provid) != int and type(provid) != unicode \
                and type(provid) != str:
            log.e('params fetching error')
            res = {'idx': self.ss_idx, 'ret': 1, 'msg': etc.err_500, 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return

        if type(provid) == str or type(provid) == unicode:
            if provid.isdigit():
                provid = int(provid)
            else:
                log.e('params fetching error')
                res = {'idx': self.ss_idx, 'ret': 1, 'msg': etc.err_500, 'res': {}}
                self.write(json.dumps(res))
                self.finish()
                return

        if provid != 0:
            provid_list = [0, provid]
        else:
            provid_list = [0]

        topic_list = data_topic_title_mysql\
            .get_topic_title_by_provid_list(provid_list, begin, limit)

        # log.i('1======%s=======' % topic_list)
        prov_item_list = data_prov_base_mysql\
            .get_prov_base_by_provid_list(provid_list)

        channel_dict = {}
        for prov_item in prov_item_list:
            if prov_item['provid'] == 0:      # provid为0时为公共频道
                channel_dict[prov_item['provid']] = u'公共频道'
            else:
                channel_dict[prov_item['provid']] =\
                    prov_item['cname'] + u'频道'

        # log.d('2======%s=======' % topic_list)

        imgid_list = []
        topicid_list = []
        for item in topic_list:
            imgid_list.append(item['imgid'])
            topicid_list.append(item['topicid'])
        img_dict = data_img_base_mysql.get_img_url_by_imgid_list(imgid_list)
        topic_hot = data_topic_note_mysql.get_topic_note_count_by_topicid_list(topicid_list)

        for item in topic_list:
            item['channel'] = channel_dict[item['provid']]
            item['imglink'] = img_dict[item['imgid']]
            item['hot'] = topic_hot.get(item['topicid'], 0)

        topic_like_list = data_topic_like_mysql.get_topic_like_by_userid(userid) #[topicid1, topicid2, ...]
        if userid and topic_like_list:

            for item in topic_list:
                if item['topicid'] in topic_like_list:
                    item['liked'] = 1
                else:
                    item['liked'] = 0
        log.i(topic_list)
        res = {'idx': self.ss_idx, 'ret': 0, 'msg': 'ok', 'res': topic_list}
        # log.d(res)
        self.write(json.dumps(res))
        self.finish()
        return


class HotHandler(BaseHandler):
    @ApiGuest
    def post(self):
        try:
            provid = self.ss_params.get('provid')
            log.i("['provid': %d]" % provid)
            if provid is None:
                log.e('params fetching error')
                res = {'idx': self.ss_idx, 'ret': 1, 'msg': etc.err_500, 'res': {}}
                self.write(json.dumps(res))
                self.finish()
                return

            cache_topic_id_list = get_topic_gallery_cache(provid)
            log.i("cache_topic_id_list = %s" % cache_topic_id_list)

            real_topic_id_list = []
            for t in cache_topic_id_list:
                if t:
                    real_topic_id_list.append(t)
                else:
                    tmp_topicid = data_topic_title_mysql\
                        .get_random_topicid(real_topic_id_list)
                    real_topic_id_list.append(tmp_topicid)

            topic_dict = data_topic_title_mysql\
                .get_topic_title_dict_by_topicid_list(real_topic_id_list)

            topic_list = []
            for topic_id in real_topic_id_list:
                tmp_topic = topic_dict.get(topic_id, None)
                if tmp_topic:
                    topic_list.append(tmp_topic)

            imgid_list = []
            for item in topic_list:
                imgid_list.append(item['imgid'])

            img_dict = data_img_base_mysql.get_img_url_by_imgid_list(imgid_list)

            for item in topic_list:
                item['imglink'] = img_dict[item['imgid']]

            res_list = [{'topicid': t['topicid'], 'imglink': t['imglink']}
                        for t in topic_list]

            res = {'idx': self.ss_idx, 'ret': 0, 'msg': 'ok', 'res': res_list}
            log.i(res)
            self.write(json.dumps(res))
            self.finish()
            return
        except Exception as e:
            log.exp(e)
            res = {'idx': 0, 'ret': 1, 'msg': 'ng', 'res': []}
            self.write(json.dumps(res))
            self.finish()
            return


class LikeTopicHandler(BaseHandler):
    @ApiHost
    def post(self):
        topicid = self.ss_params['topicid']
        userid = self.ss_user['userid']

        if not (userid and topicid):
            log.e('params fetching error')
            res = {'idx':self.ss_idx, 'ret':1, 'msg':etc.err_500, 'res':{}}
            self.write(json.dumps(res))
            self.finish()
            return
        item = {}
        item['topicid'] = topicid
        item['userid'] = userid
        result = data_topic_like_mysql.add_topic_like_item(item)
        if result:
            if not data_user_feed_mysql.add_user_feed_item({
                'userid': userid,
                'optype': data_user_feed_mysql.USER_FEED_TYPE_TOPIC_LIKE,
                'targetid': topicid,
            }):
                self._generate_res(1, '收藏失败', 'add_topic_user_feed')
                return
            res = {'idx': self.ss_idx, 'ret': 0, 'msg': '收藏成功', 'res': {}}
        else:
            res = {'idx': self.ss_idx, 'ret': 1, 'msg': '收藏失败', 'res': {}}
        self.write(json.dumps(res))
        self.finish()
        return


class DelTopicLikeHandler(BaseHandler):
    @ApiHost
    def post(self):
        topicid = self.ss_params['topicid']
        userid = self.ss_user['userid']

        if not (userid and topicid):
            log.e('params fetching error')
            res = {'idx':self.ss_idx, 'ret':1, 'msg':etc.err_500, 'res':{}}
            self.write(json.dumps(res))
            self.finish()
            return
        result = data_topic_like_mysql.del_topic_like_by_topicid_and_userid(topicid, userid)
        if result:
            if not data_user_feed_mysql.del_user_feed({
                'userid': userid,
                'optype': data_user_feed_mysql.USER_FEED_TYPE_TOPIC_LIKE,
                'targetid': topicid,
            }):
                self._generate_res(1, '删除动态失败', 'add_note_like_feed')
                return
            res = {'idx': self.ss_idx, 'ret': 0, 'msg': '取消收藏成功', 'res': {}}
        else:
            res = {'idx': self.ss_idx, 'ret': 0, 'msg': '取消收藏失败', 'res': {}}
        self.write(json.dumps(res))
        self.finish()
        return

class ListOneHandler(BaseHandler):
    @ApiGuest
    def post(self, *args, **kwargs):
        topicid = self.ss_params['topicid']

        if not topicid:
            log.e('params fetching error')
            res = {'idx':self.ss_idx, 'ret':1, 'msg':etc.err_500, 'res':{}}
            self.write(json.dumps(res))
            self.finish()
            return
        topic_title = data_topic_title_mysql.get_topic_title_by_topicid(topicid)

        if not topic_title:
            log.e('topic not found')
            res = {'idx': self.ss_idx, 'ret': 1, 'msg': u'没有这个话题', 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return

        channel = data_prov_base_mysql.get_prov_base_by_provid(topic_title['provid'])
        channel_name = channel['cname'] + u'频道'
        liked_item = data_topic_like_mysql.get_topic_like_count_by_topicid(topicid)
        img_link = data_img_base_mysql.get_img_url_by_imgid(topic_title['imgid'])
        topic_title['imglink'] = img_link if img_link else ""
        topic_title['channel'] = channel_name
        if liked_item is None:
            topic_title['hot'] = 0
        else:
            topic_title['hot'] = liked_item
        topic_title['liked'] = 0
        if self.current_user:
            like = data_topic_like_mysql.get_topic_like_by_topicid_userid(topicid, self.current_user['userid'])
            if like is not None:
                topic_title['liked'] = 1
        res = {'idx':self.ss_idx, 'ret': 0, 'msg': 'ok', 'res': topic_title}
        self.write(json.dumps(res))
        self.finish()
        return

class ApiNotFoundHandler(BaseHandler):
    def get(self):
        raise tornado.web.HTTPError(503)

    @tornado.web.asynchronous
    def post(self):
        log.i('503')
        res = {'idx': -1, 'ret': -5, 'msg': etc.err_no_api, 'res': {}}
        self.write(json.dumps(res))
        self.finish()
